package com.linq.cool.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linq.cool.beauty.domain.BeautyBrand;
import com.linq.cool.beauty.domain.BeautyBrandProductCategory;
import com.linq.cool.beauty.dto.BeautyBrandDTO;
import com.linq.cool.beauty.dto.BeautyBrandQueryDTO;
import com.linq.cool.beauty.mapper.BeautyBrandMapper;
import com.linq.cool.beauty.service.BeautyBrandService;
import com.linq.cool.common.constants.Constants;
import com.linq.cool.common.core.exception.BusinessException;
import com.linq.cool.common.core.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: yqlin
 * @Date: 2021/2/6 12:51
 * @Description:
 * @Version: 1.0.0
 */

@Service
public class BeautyBrandServiceImpl extends ServiceImpl<BeautyBrandMapper, BeautyBrand> implements BeautyBrandService {
    @Autowired
    private BeautyBrandProductCategoryServiceImpl beautyBrandProductCategoryService;

    @Override
    public IPage<BeautyBrand> listByPage(IPage<BeautyBrand> page, BeautyBrandQueryDTO dto) {
        return this.page(page, this.getLambdaQueryWrapper(dto));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveBrand(BeautyBrandDTO dto) {
        BeautyBrand brand = new BeautyBrand();
        BeanUtils.copyProperties(dto, brand);
        if (this.checkNameUnique(brand)) {
            throw new BusinessException("新增品牌'" + brand.getName() + "'失败，名称已存在");
        }
        // 将品牌-分类存库 拿过来的是二级分类的id 也就是 三级分类id父id
        // 判断分类ID集合是否为空，不为空就入库
        if (CollectionUtils.isNotEmpty(dto.getProductCategoryIds())) {
            List<BeautyBrandProductCategory> brandProductCategoryList = dto.getProductCategoryIds()
                    .stream().map(pcid -> {
                        BeautyBrandProductCategory brandProductCategory = new BeautyBrandProductCategory();
                        brandProductCategory.setProductCategoryId(pcid)
                                .setBrandId(brand.getId());
                        return brandProductCategory;
                    }).collect(Collectors.toList());
            // 存库
            beautyBrandProductCategoryService.saveBatch(brandProductCategoryList);
        }
        return this.save(brand);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateBrand(BeautyBrandDTO dto) {
        BeautyBrand brand = new BeautyBrand();
        BeanUtils.copyProperties(dto, brand);
        if (this.checkNameUnique(brand)) {
            throw new BusinessException("新增品牌'" + brand.getName() + "'失败，名称已存在");
        }
        // 将品牌-分类存库
        // 判断分类ID集合是否为空，不为空就入库
        if (CollectionUtils.isNotEmpty(dto.getProductCategoryIds())) {
            // 清空之前 存入的品牌-商品分类中间表信息
            beautyBrandProductCategoryService.remove(new LambdaQueryWrapper<BeautyBrandProductCategory>()
                                                             .eq(BeautyBrandProductCategory::getBrandId, brand.getId())
            );
            List<BeautyBrandProductCategory> brandProductCategoryList = dto.getProductCategoryIds()
                    .stream().map(pcid -> {
                        BeautyBrandProductCategory brandProductCategory = new BeautyBrandProductCategory();
                        brandProductCategory.setProductCategoryId(pcid)
                                .setBrandId(brand.getId());
                        return brandProductCategory;
                    }).collect(Collectors.toList());
            // 存库
            beautyBrandProductCategoryService.saveBatch(brandProductCategoryList);
        }
        return this.updateById(brand);
    }

    /**
     * 品牌名称唯一
     *
     * @param brand
     *
     * @return
     */
    private boolean checkNameUnique(BeautyBrand brand) {
        Long brandId = null == brand.getId() ? -1L : brand.getId();
        BeautyBrand one = this.getOne(new LambdaQueryWrapper<BeautyBrand>()
                                              .select(BeautyBrand::getId, BeautyBrand::getName)
                                              .eq(BeautyBrand::getName, brand.getName())
        );
        // 判断id是否一致 不一致就代表 唯一 false
        return null != one && !brandId.equals(one.getId());
    }

    private LambdaQueryWrapper<BeautyBrand> getLambdaQueryWrapper(BeautyBrandQueryDTO dto) {
        return new LambdaQueryWrapper<BeautyBrand>()
                .orderByAsc(BeautyBrand::getSort)
                .eq(StringUtils.checkValNotNull(dto.getName()), BeautyBrand::getName, dto.getName())
                .eq(StringUtils.checkValNotNull(dto.getStatus()), BeautyBrand::getStatus, dto.getStatus())
                .between(StringUtils.checkValNotNull(dto.getParams().get(Constants.BEGIN_TIME)), BeautyBrand::getGmtCreate, dto.getParams().get(Constants.BEGIN_TIME), dto.getParams().get(Constants.END_TIME))
                ;
    }
}
